package com.dhcc.sds.custom.controller;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.cdc.busi.service.ICdcEpisodeService;
import com.dhcc.cdc.sys.cache.config.CdcConfigCache;
import com.dhcc.cdc.sys.service.IConfigurationService;
import com.dhcc.core.config.properties.SysProperties;
import com.dhcc.core.framework.base.controller.BaseController;
import com.dhcc.core.framework.base.warpper.EmptyWarpper;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.result.page.PageFactory;
import com.dhcc.core.framework.security.ShiroKit;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.modules.system.entity.User;
import com.dhcc.sds.base.entity.SdsQcentityEntity;
import com.dhcc.sds.base.entity.SdsQcentityRuleEntity;
import com.dhcc.sds.base.service.ISdsCommonService;
import com.dhcc.sds.base.service.ISdsQcentityRuleService;
import com.dhcc.sds.base.service.ISdsQcentityService;
import com.dhcc.sds.busi.entity.SdsQcincaseEntity;
import com.dhcc.sds.busi.entity.SdsQcincaseOperlogEntity;
import com.dhcc.sds.busi.service.ISdsMedicalGroupService;
import com.dhcc.sds.busi.service.ISdsQcFormShowService;
import com.dhcc.sds.busi.service.ISdsQcfitemExecresultService;
import com.dhcc.sds.custom.service.ISdsCusMrlistService;
import com.dhcc.sds.standard.dto.CdcEpisodeDto;
import com.dhcc.sds.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * 病历入组
 *
 * @ClassName: SdsCustomGroupController
 * @Description: TODO
 * @author yhw
 * @date 2024-06-26 10:33:15
 */
@Controller
@RequestMapping("${sys.backendPath}/sds/sdscusmrlist")
public class SdsCusMrlistController extends BaseController {

    private String PREFIX = "/backend/sds/sdscusmrlist/";

    @Autowired
    private ISdsCusMrlistService sdsCusMrlistService;

    @Autowired
    private ISdsCommonService sdsCommonService;

    @Autowired
    private ISdsQcentityService sdsQcentityService;

    @Autowired
    private SysProperties sysPro;


    /**
     * 跳转到病历入组列表首页
     */
    @RequestMapping("/index")
    public String index(Model model){
        Date lastDay = DateUtil.getEndDayOfMonth();
        DateTime firstday = DateUtil.getDateByDay(DateTime.of(lastDay), -180);
        //JSONObject list = sdsQcentityService.getQcentity();
        //获取科室信息
        JSONObject deptMap = sdsCommonService.findDeptList();
        JSONObject hospMap = sdsCommonService.findHospList();

        JSONArray entityMap = sdsCommonService.getEntityMap("Custom");
        // 单病种医生是否可以直接上报配置
        String formCheckType = CdcConfigCache.me().getValueByKey("SDS", "SDFormCheckType");
        // 是否启用过程质控
        String enableIPQC = CdcConfigCache.me().getValueByKey("SDS", "EnableIPQCModule");
        model.addAttribute("formCheckType", formCheckType);
        model.addAttribute("enableIPQC", enableIPQC);
        model.addAttribute("startDate", firstday);
        model.addAttribute("endDate", lastDay);
        model.addAttribute("entityMap", entityMap);
        model.addAttribute("hospMap", hospMap);
        model.addAttribute("deptMap", deptMap);
        return PREFIX + "sdscustomgroup.html";
    }


    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam Map<String, Object> params) {
        Page<CdcEpisodeDto> page = new PageFactory<CdcEpisodeDto>().defaultPage();
        List<CdcEpisodeDto> result = this.sdsCusMrlistService.pageEpisodeByDateAndFormStatus(page,params);
        page.setRecords((List<CdcEpisodeDto>) new EmptyWarpper(result).warp());
        return R.packForBT(page);
    }
    /**
     * @Desc 生成excel文件
     * @param params
     * @return
     * @Author yhw
     * @Date 2024年06月27日016:05:00
     */
    @RequestMapping(value = "/excludeindex")
    public String excludeIndex(@RequestParam Map<String, Object> params, Model model) {
        Long mrListId = Long.valueOf(params.get("mrListId").toString());
        Long entityId = Long.valueOf(params.get("entityId").toString());
        String execUser = "";
        if (CommonUtil.isNotEmpty(params.get("execUser"))) {
            execUser = java.net.URLDecoder.decode(params.get("execUser").toString());
        } else {
            User user = ShiroKit.getUser();
            execUser = user.getLoginName();
        }
        SdsQcentityEntity sdsQcentityEntity = sdsQcentityService.selectById(entityId);
        model.addAttribute("mrListId", mrListId);
        model.addAttribute("entityDesc", sdsQcentityEntity.getBtDesc());
        model.addAttribute("execUser", execUser);
        return PREFIX + "sdscustomexclude.html";
    }

    @RequestMapping(value = "/changestatus")
    @ResponseBody
    public Object changeStatus(@RequestParam Map<String, Object> params) {
        sdsCusMrlistService.changeStatus(params);
        return R.ok();
    }


    @RequestMapping(value = "/createExcel")
    @ResponseBody
    public Object createExcel(@RequestParam Map<String, Object> params) {
        // 查询登录用户关联科室
        List<String> deptIds = sdsCommonService.getDeptIdsBySysUser();
        params.put("userLinkDepts", deptIds);
        String fileName = this.sdsCusMrlistService.createExcel(params);
        return R.ok(fileName);
    }


    /**
     * @Desc 下载生成的Excel文件  .+ 后面的解决小数点取值不全问题
     * @param fileName
     * @param resp
     * @throws IOException
     * @Author wujiafeng
     * @Date 2018年11月14日 上午11:26:34
     */
    @RequestMapping(value = "excelDown/{fileName:.+}")
    @ResponseBody
    public void excelDown(@PathVariable String fileName, HttpServletResponse resp) throws IOException{
        String filePath = sysPro.getSysHome()+"file_download/sds/customgroup/";
        String excelFile = filePath + fileName;
        File file = new File(excelFile);
        if(file.exists()){
            //将文件名设置为中文
            byte[] tmpb = fileName.getBytes("GBK");
            String fileNameCN = new String(tmpb, "8859_1");
            resp.setContentType("application/octet-stream");
            resp.setHeader("Content-Disposition","attachment;filename=" + fileNameCN);
            resp.setContentLength((int) file.length());
            //打开指定文件流
            BufferedInputStream fileInputStream = new BufferedInputStream(new FileInputStream(excelFile));
            //写出流信息
            byte[] bytes =new byte[1024];
            OutputStream os = resp.getOutputStream();
            BufferedOutputStream fosObject = new BufferedOutputStream(os);
            while (fileInputStream.read(bytes)!=-1) {
                fosObject.write(bytes);
            }
            fileInputStream.close();
            fosObject.close();
            os.flush();
            os.close();
        }
    }
}
